<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拦截器</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
    
</head>
<body>
    <button>发送请求</button>
    <button>发送请求</button>

    <script>

        let btns = document.querySelectorAll('button');

        //添加请求拦截器回调  then
        axios.interceptors.request.use((config) => {
            //成功回调
            // console.log(config);
            config.params = {
                vip: 9
            }
            //显示进度条
            NProgress.start();
            //必须要函数中, 返回 config 配置对象
            return config;
        }, (err) => {
            //失败回调
            console.log(err);
            //一般返回一个失败的 promise 对象
            return Promise.reject(err);
        });


        //添加响应拦截器回调            Promise 成功的结果值
        axios.interceptors.response.use((response) => {
            //成功回调
            console.log(response);
            NProgress.done();
            //需要返回一个值
            return response.data;
            // return Promise.reject('error');
        }, (err) => {
            console.log('请求失败啦!!');
            NProgress.done();
            //失败回调
            return Promise.reject(err);
        })


        btns[0].onclick = function(){
            axios('http://127.0.0.1:8090/server')
            .then(res => {
                console.log(res);
            }, err => {
                console.warn(err);
            })
        }

        btns[1].onclick = function(){
            axios('http://127.0.0.1:8090/test')
            .then(res => {
                console.log(res);
            }, err => {
                console.warn(err);
            })
        }
    </script>
</body>
</html>